<template>
  <BasicModal v-bind="$attrs" @ok="handleDownload" @register="registerModal">
    <template v-if="ifAttachment">
      <div style="margin-bottom: 10px" v-for="(item, index) in attachmentList" :key="item.url">
        {{ index + 1 }}、{{ item.name || '--' }}
      </div>
    </template>
    <template v-else>
      <AImage :style="{ height: imageHeight + 'px' }" :src="record['bluePrintImgUrl']" />
    </template>
  </BasicModal>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import { downloadFileZip } from '@/utils';
  import { Image as AImage } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { downloadByUrl } from '@/utils/file/download';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { SalesProductBatchModel } from 'mc-c2b2m-operator-api/types/production';

  const type = ref<string>('');
  const record = ref<SalesProductBatchModel | {}>({});
  // 图片高度
  const imageHeight = ref<number>(0);
  // 是否原文件预览
  const ifAttachment = computed(() => type.value === '1');
  // 原文件列表
  const attachmentList = computed(() => {
    return (record.value?.['attachmentList'] || []).filter((item: any) => item.url);
  });
  const [registerModal, { setModalProps, changeOkLoading }] = useModalInner(async (data) => {
    imageHeight.value = 0;
    type.value = data.type;
    record.value = data.record;
    setModalProps({
      minHeight: 50,
      okText: '下载文件',
      confirmLoading: false,
      title: `查看${ifAttachment.value ? '原文件' : '蓝纸'}`,
    });
    if (!ifAttachment.value) {
      const image = new Image();
      image.src = record.value['bluePrintImgUrl'];
      image.onload = () => {
        imageHeight.value = (492 * image.height) / image.width;
      };
    }
  });

  const { createMessage } = useMessage();
  // 下载文件
  async function handleDownload() {
    try {
      changeOkLoading(true);
      const {
        spuName,
        orderCode,
        attachmentList,
        bluePrintImgUrl: url,
        orderPlacerUserPhone: phone,
      } = record.value as SalesProductBatchModel;
      ifAttachment.value
        ? await downloadFileZip(attachmentList, `${orderCode}+${spuName}+${phone}`)
        : downloadByUrl({ url });
      createMessage.success('下载成功！');
    } catch (e) {
      createMessage.error(`下载失败：${e}`);
    } finally {
      changeOkLoading(false);
    }
  }
</script>
